import axios from "axios";
import { ClientStorage } from 'common-list'

axios.interceptors.request.use(
  config => {
    //post请求头
    config.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";

    // 跨域请求携带Cookie信息
    config.withCredentials = true

    //设置超时
    config.timeout = 60000

    // 设置身份验证信息（跨域时有效）
    // config.headers.Authorization = cookie
    let userInfo = ClientStorage.get('userInfo', false, true) //user.userInfo
    if (!userInfo) {
      userInfo = {}
    }
    let accessToken = userInfo.accessToken
    if (accessToken) {
      config.headers.Authorization = 'Bearer ' + accessToken
    }
    return config;

  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {

    // if (response.status == 200) {
    return Promise.resolve(response.data);
    // } else {
    //   return Promise.reject(response.data);
    // }
  },
  async ({ error, response }) => {
    debugger
    if (response && response.status === 401 && (response.data?.error === 'jwt expired' || response.data?.error === "Authentication Error")) {
      ///const user = store.state
      let userInfo = ClientStorage.get('userInfo', false, true) //user.userInfo
      if (!userInfo) {
        userInfo = {}
      }
      const rToken = userInfo.refreshToken;
      if (rToken) {
        let res = await refreshToken({ refreshToken: rToken });// 去服务器刷新token
        if (res?.errno === 0) {
          userInfo.accessToken = res.data.accessToken // 更新token后替换
          ClientStorage.set('userInfo', userInfo, false, true)
          return axios.request(response.config);
        }
      }

    }

    return Promise.reject(error)
  }
);

function refreshToken(data) {
  return axios({
    url: '/api/user/refreshjwttoken',
    method: 'post',
    data
  })
}
export default axios;